/*
 * @Author: Eureka 
 * @Date: 2020-09-03 16:00:47 
 * @Last Modified by: Eureka
 * @Last Modified time: 2022-01-19 18:50:11
 * 
 */

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:senkoo_platform/Utils/hex_color_utils.dart';
import 'package:senkoo_platform/Utils/set_edge_insets.dart';
import 'package:senkoo_platform/base_print_log/base_print_log.dart';
import 'package:senkoo_platform/base_provider/base_provider.dart';
import 'package:senkoo_platform/base_import/base_import.dart';
import 'package:senkoo_platform/base_router/base_router_util.dart';
import 'package:senkoo_platform/config/config.dart';

abstract class BaseFuntion {
  State? _baseState;
  late BuildContext _baseContext;
  bool _isTopBarShow = true; //状态栏是否显示
  bool _isAppBarShow = true; //导航栏是否显示
  bool _isLeftBackShow = true; //左边返回按钮是否显示
  bool _isNavigationBarShow = false; //底部导航栏是否显示
  bool _brightnessBool = true; //修改brightness
  bool prohibitDrawerBool = false; //默认禁止侧边
  BaseProvider provider = BaseProvider();
  Color _topBarColor = Standard.colorFFFFFF; //状态栏颜色
  Color _appBarColor = Standard.colorFFFFFF; //顶部导航栏颜色
  Color _navigationBarColor = Standard.color000000; //底部导航栏颜色
  // ignore: unused_field
  Color _appBarContentColor = Standard.color000000; //顶部导航栏字颜色
  Color _iconColor = Standard.color000000;
  int _centerFlex = 1; //title中间flex默认值
  String? _appBarTitle;
  final _appBarTitles = [
    '首页',
    '个人中心',
  ];
  List _tabImages = [];
  List<BottomNavigationBarItem>? _list;

  void initBaseCommon(State state, BuildContext context) {
    _baseState = state;
    _baseContext = context;
    if (AppConfig.isDebug) {
      _appBarTitle = getClassName();
    }
  }

  Widget getBaseView(BuildContext context) {
    return ChangeNotifierProvider<BaseProvider>(
      create: (_) => provider,
      child: Container(
        color: Standard.colorFAFAFA,
        width: getScreenWidth(),
        height: getScreenHeight(),
        child: Column(
          children: <Widget>[
            getBaseTopBar(),
            getBaseAppBar(),
            Expanded(
              child: Container(
                color: Standard.colorFAFAFA,
                child: buildWidget(context),
              ),
            ),
            getNavigationBar()
          ],
        ),
      ),
    );
  }

  Widget getDrawer() {
    return Container();
  }

  Widget getBaseTopBar() => Offstage(
        offstage: !_isTopBarShow,
        child: getTopBar(),
      );

  Widget getBaseAppBar() => Offstage(
        offstage: !_isAppBarShow,
        child: getAppBar(),
      );

  Widget getNavigationBar() => Offstage(
        offstage: !_isNavigationBarShow,
        child: getButtonNavigationBar(),
      );

  ///设置状态栏，可以自行重写拓展成其他的任何形式
  Widget getTopBar() => Container(
        width: getScreenWidth(),
        height: getTopBarHeight(),
        color: _topBarColor,
        child: _brightnessBool
            // ignore: deprecated_member_use
            ? AppBar(elevation: 0.0, backgroundColor: _topBarColor)
            // ignore: deprecated_member_use
            : AppBar(elevation: 1, backgroundColor: _topBarColor),
      );

  ///导航栏 appBar 可以重写
  Widget getAppBar() => Container(
      padding: setEdgeInsets(),
      height: getAppBarHeight(),
      width: getScreenWidth(),
      color: _appBarColor,
      child: Flex(
        direction: Axis.horizontal,
        children: <Widget>[
          Expanded(
              flex: 1,
              child: GestureDetector(
                  onTap: clickAppBarBack,
                  child: Offstage(
                      offstage: !_isLeftBackShow,
                      child: Container(
                        color: Colors.transparent,
                        child: getAppBarLeft(),
                      )))),
          Expanded(
            flex: _centerFlex,
            child: getAppBarCenter(),
          ),
          Expanded(flex: 1, child: Container())
        ],
      ));

  ///导航栏appBar左边部分 ，不满足可以自行重写
  Widget getAppBarLeft({Color? iconColor}) => Row(
        children: [
          Container(
            child: Icon(
              Icons.chevron_left_sharp,
              size: 24.w,
              color: iconColor ?? _iconColor,
            ),
            margin: setEdgeInsets(left: 12),
          )
        ],
      );

  void clickAppBarBack() {
    if (Navigator.canPop(_baseContext)) {
      RouterUtil.popPage(_baseContext);
    } else {
      //说明已经没法回退了 ， 可以关闭了
      finishDartPageOrApp();
    }
  }

  ///关闭最后一个 flutter 页面 ， 如果是原生跳过来的则回到原生，否则关闭app
  void finishDartPageOrApp() {
    SystemNavigator.pop();
  }

  ///导航栏appBar中间部分 ，不满足可以自行重写
  Widget getAppBarCenter() => Container(
          child: text(
        textString: '$_appBarTitle',
        textWeight: medium,
        textSize: 18.sp,
        textColor: _appBarContentColor,
        textAligin: textAlignCenter,
      ));

  Widget getButtonNavigationBar() => Consumer<BaseProvider>(
        builder: (_, provider, __) => BottomNavigationBar(
          backgroundColor: _navigationBarColor,
          items: buildBottomNavigationBarItem()!,
          type: BottomNavigationBarType.fixed,
          currentIndex: provider.value,
          elevation: 5.0,
          iconSize: 21.0,
          selectedLabelStyle: const TextStyle(
              fontWeight: FontWeight.w500, decoration: TextDecoration.none),
          unselectedLabelStyle: const TextStyle(
              fontWeight: FontWeight.w500, decoration: TextDecoration.none),
          selectedFontSize: 12.sp,
          unselectedFontSize: 12.sp,
          selectedItemColor: HexColor('#333333'),
          unselectedItemColor: HexColor('#999999'),
          onTap: (index) {
            provider.value = index;
          },
        ),
      );

  List<BottomNavigationBarItem>? buildBottomNavigationBarItem() {
    _tabImages = [
      [
        {
          'image': Container(
            color: Colors.blue,
            width: 21.w,
            height: 21.w,
          ),
          'select': true,
        },
        {
          'image': Container(
            color: Colors.blue,
            width: 21.w,
            height: 21.w,
          ),
          'select': true,
        }
      ],
      [
        {
          'image': Container(
            color: Colors.blue,
            width: 21.w,
            height: 21.w,
          ),
          'select': true,
        },
        {
          'image': Container(
            color: Colors.blue,
            width: 21.w,
            height: 21.w,
          ),
          'select': true,
        },
      ],
    ];

    _list = List.generate(2, (i) {
      return BottomNavigationBarItem(
        icon: _tabImages[i][0]['image'],
        activeIcon: _tabImages[i][1]['image'],
        label: _appBarTitles[i],
        // ignore: deprecated_member_use
        // title: Padding(
        //   padding: const EdgeInsets.only(top: 4.0),
        //   child: Text(
        //     _appBarTitles[i],
        //     style: const TextStyle(decoration: TextDecoration.none),
        //     key: Key(_appBarTitles[i]),
        //   ),
        // )
      );
    });
    return _list;
  }

  /*
   * 以上为widget
   */

  ///设置状态栏隐藏或者显示
  /// ignore: invalid_use_of_protected_member
  void setTopBarVisible(bool isVisible) => _baseState!.setState(() {
        _isTopBarShow = isVisible;
      });

  ///默认这个状态栏下，设置颜色
  /// ignore: invalid_use_of_protected_member
  void setTopBarBackColor(Color color) => _baseState!.setState(() {
        _topBarColor = color;
      });

  //设置appbar 为 dark 色系
  // ignore: invalid_use_of_protected_member
  void setAppbarDark({bool show = true}) => _baseState!.setState(() {
        _brightnessBool = show;
      });

  ///设置导航栏隐藏或者显示
  /// ignore: invalid_use_of_protected_member
  void setAppBarVisible(bool isVisible) => _baseState!.setState(() {
        _isAppBarShow = isVisible;
      });

  ///默认这个导航栏下，设置颜色
  /// ignore: invalid_use_of_protected_member
  void setAppBarBackColor(Color color) => _baseState!.setState(() {
        _appBarColor = color;
      });
// ignore: invalid_use_of_protected_member
  void setAppBarTitle(String title) => _baseState!.setState(() {
        _appBarTitle = title;
      });

  ///设置导航栏的字体以及图标颜色
  /// ignore: invalid_use_of_protected_member
  void setAppBarContentColor(Color contentColor) => _baseState!.setState(() {
        _appBarContentColor = contentColor;
      });

  ///设置导航栏返回颜色
  /// ignore: invalid_use_of_protected_member
  void setAppBarIconColor(Color iconColor) => _baseState!.setState(() {
        _iconColor = iconColor;
      });

  ///设置底部导航栏隐藏或者显示
  /// ignore: invalid_use_of_protected_member
  void setNavigationBarVisible(bool isVisible) => _baseState!.setState(() {
        _isNavigationBarShow = isVisible;
      });

  ///设置底部导航栏隐藏或者显示
  /// ignore: invalid_use_of_protected_member
  void setNavigationBarBackColor(Color color) => _baseState!.setState(() {
        _navigationBarColor = color;
      });

  ///设置导航栏隐藏或者显示
  /// ignore: invalid_use_of_protected_member
  void setLeftBackVisible(bool isVisible) => _baseState!.setState(() {
        _isLeftBackShow = isVisible;
      });

  ///设置居中flex
  /// ignore: invalid_use_of_protected_member
  void setCenterFlex({required int flex}) => _baseState!.setState(() {
        _centerFlex = flex;
      });

  ///设置居中flex
  /// ignore: invalid_use_of_protected_member
  void setProhibitDrawer(bool isVisible) => _baseState!.setState(() {
        prohibitDrawerBool = isVisible;
      });

  //获取当前类名
  String? getClassName() {
    if (_baseState == null) {
      return null;
    }
    String className = _baseState.toString();
    try {
      if (AppConfig.isDebug) {
        className = className.substring(0, className.indexOf("#"));
      }
    } catch (e) {
      className = 'error';
    }
    return className;
  }

  ///返回屏幕宽度
  double getScreenWidth() => MediaQuery.of(_baseContext).size.width;

  ///返回屏幕宽度
  double getScreenHeight() => MediaQuery.of(_baseContext).size.height;

  ///返回状态栏高度
  double getTopBarHeight() => MediaQuery.of(_baseContext).padding.top;

  ///返回appbar高度，也就是导航栏高度
  double getAppBarHeight() => kToolbarHeight;

  double getNavigationBarHeight() => MediaQuery.of(_baseContext).padding.bottom;

  ///初始化一些变量 相当于 onCreate ， 放一下 初始化数据操作
  void onCreate();

  ///相当于onResume, 只要页面来到栈顶， 都会调用此方法，网络请求可以放在这个方法
  void onResume();

  ///页面被覆盖,暂停
  void onPause();

  ///返回UI控件 相当于setContentView()
  Widget buildWidget(BuildContext context);

  ///页面注销方法
  void onDestory() {}

  ///app切回到后台
  void onBackground() => {
        PrintUtil.d('回到后台'),
      };

  ///app切回到前台
  void onForeground() => {
        PrintUtil.d('回到前台'),
        // jpush.setBadge(0)
      };

  Future<void> initPlatformState() async {
    // FlutterAliyunPush.reigistOnRegistSuccess((msg) {
    //   print(msg);
    // });
  }

  Future<bool> requestPermission() async {
    const permissions = Permission.locationWhenInUse;
    var status = await permissions.status;
    if (status == PermissionStatus.granted) {
      return true;
      // undetermined
    } else if (status == PermissionStatus.denied) {
      status = await permissions.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        showToast("无定位权限,请先设置定位权限");
        return false;
      }
    } else {
      showToast("无定位权限,请先设置定位权限");
      return false;
    }
  }
}
